package cn.tedu.ivos.utils;

import com.alibaba.fastjson2.JSON;
import io.jsonwebtoken.*;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

@Slf4j
public class JwtUtils {
    /**
     * 令牌自定义标识
     */
    public static final String AUTHENTICATION = "Authorization";

    /**
     * 令牌前缀
     */
    public static final String PREFIX = "Bearer ";

    /**
     * 令牌秘钥
     */
    public final static String SECRET = "abcdefghijklmnopqrstuvwxyz";
    private String secret;
    private static final String CLAIM_PAYLOAD = "payload";
    public static<T> String generateToken(T payload) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_PAYLOAD, JSON.toJSONString(payload));
        JwtBuilder builder = null;
        try{
            builder = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512,SECRET.getBytes(StandardCharsets.UTF_8));
        }catch (Exception e){
            log.error("failed to create jwt builders,error message:{}",e.getMessage());
            throw new JwtException("token create error",e);
        }
        return builder.compact();
    }
    public static <T>T parseToken(String token, Class<? extends T> clazz) {
        Jws<Claims> jws = null;
        if (StringUtils.isEmpty(token)){
            return null;
        }
        try {
            jws = Jwts.parser().setSigningKey(SECRET.getBytes(StandardCharsets.UTF_8)).parseClaimsJws(token);
        } catch(Exception e){
            log.error("jwt parse error:{}",e.getMessage());
            throw new JwtException("jwt parse error",e);
        }
        Claims claims = (Claims)jws.getBody();
        String loginTokenJson = (String)claims.get(CLAIM_PAYLOAD);
        return JSON.parseObject(loginTokenJson, clazz);
    }

    public static String getRequestToken(HttpServletRequest request)
    {
        String token = request.getHeader(AUTHENTICATION);
        if (!StringUtils.isEmpty(token) && token.startsWith(PREFIX))
        {
            token = token.replace(PREFIX, "");
        }
        return token;
    }
}
